using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Text;

namespace limpalex.bbparser.Tokens
{
    internal sealed class TagToken : BaseToken
    {
        public override TokenType Type
        {
            get { return TokenType.Tag; }
        }

        private string defaultValue = string.Empty;
        private readonly NameValueCollection attributes = new NameValueCollection();

        public bool IsClosing
        {
            get; set;
        }

        public bool IsOpening
        {
            get { return !IsClosing; }
        }

        public string Name
        {
            get; set;
        }

        public string DefaultValue
        {
            get { return defaultValue; }
            set { defaultValue = value; }
        }

        public NameValueCollection Attributes
        {
            get
            {
                return attributes;
            }
        }

        [IndexerName("AttributeValue")]
        public string this[string attributeName]
        {
            get
            {
                return attributes[attributeName];
            }
        }

        public override string Text
        {
            get { return string.Empty; }
        }

        public override string ToString()
        {
            if ( IsClosing )
            {
                return string.Format("[/{0}]", Name);
            }

            if (!string.IsNullOrEmpty(defaultValue))
                return string.Format("[{0}={1}]", Name, defaultValue);

            if (attributes.Count == 0)
                return string.Format("[{0}]", Name);

            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("[{0}", Name);
            foreach ( string key in attributes.AllKeys )
            {
                builder.AppendFormat(" {0}={1}", key, attributes[key]);
            }
            builder.Append("]");

            return builder.ToString();
        }

        public bool HasAttribute(string name)
        {
            return Array.Exists(attributes.AllKeys, key => key.Equals(name));
        }

        public Replacement Replacement { get; set; }

    }

}
